#include "wagemanagementdialog.h"
#include "wageeditdialog.h"
#include <QMessageBox>
#include <QSqlError>
#include <QDebug>
#include <QSqlQuery>
#include <QHeaderView>
#include <QTableWidgetItem>
#include <QHBoxLayout>
#include <QWidget>
#include <QPushButton>

WageManagementDialog::WageManagementDialog(QWidget *parent)
    : QDialog(parent), ui(new Ui::WageManagementDialog)
{
    ui->setupUi(this);
    
    // 初始化表格
    ui->wageTable->setColumnCount(5);
    ui->wageTable->setHorizontalHeaderLabels(QStringList() << "玩具名称" << "总工价" << "员工工价" << "利润" << "操作");
    ui->wageTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    
    // 连接信号和槽
    connect(ui->addButton, &QPushButton::clicked, this, &WageManagementDialog::onAddWage);
    connect(ui->searchButton, &QPushButton::clicked, this, &WageManagementDialog::onSearch);
    connect(ui->resetButton, &QPushButton::clicked, this, &WageManagementDialog::onResetSearch);
    connect(ui->wageTable, &QTableWidget::itemSelectionChanged, this, &WageManagementDialog::validateInput);
    
    loadToyData();
    loadWageData();
    
    // 初始验证
    validateInput();
}

// 加载玩具数据
void WageManagementDialog::loadToyData()
{
    m_toyMap.clear();
    // 清空下拉框，但保留"全部"选项
    ui->toySearchCombo->clear();
    ui->toySearchCombo->addItem("全部", -1);
    
    QSqlQuery query("SELECT id, name FROM toys ORDER BY name");
    while (query.next()) {
        int id = query.value(0).toInt();
        QString name = query.value(1).toString();
        m_toyMap[name] = id;
        ui->toySearchCombo->addItem(name, id);
    }
}

void WageManagementDialog::loadWageData()
{
    ui->wageTable->setRowCount(0);
    
    QSqlQuery query("SELECT wm.id, t.name, wm.total_wage, wm.employee_wage, wm.profit "
                   "FROM wage_management wm "
                   "JOIN toys t ON wm.toy_id = t.id "
                   "ORDER BY t.name");
    
    int row = 0;
    while (query.next()) {
        int id = query.value(0).toInt();
        QString toyName = query.value(1).toString();
        double totalWage = query.value(2).toDouble();
        double employeeWage = query.value(3).toDouble();
        double profit = query.value(4).toDouble();
        
        ui->wageTable->insertRow(row);
        
        // 玩具名称
        QTableWidgetItem *toyItem = new QTableWidgetItem(toyName);
        toyItem->setData(Qt::UserRole, id); // 存储工价记录ID
        ui->wageTable->setItem(row, 0, toyItem);
        
        // 总工价 (精确到厘)
        QTableWidgetItem *totalWageItem = new QTableWidgetItem(QString::number(totalWage, 'f', 3));
        ui->wageTable->setItem(row, 1, totalWageItem);
        
        // 员工工价 (精确到厘)
        QTableWidgetItem *employeeWageItem = new QTableWidgetItem(QString::number(employeeWage, 'f', 3));
        ui->wageTable->setItem(row, 2, employeeWageItem);
        
        // 利润 (精确到厘)
        QTableWidgetItem *profitItem = new QTableWidgetItem(QString::number(profit, 'f', 3));
        ui->wageTable->setItem(row, 3, profitItem);
        
        // 操作按钮
        QPushButton *editBtn = new QPushButton("编辑");
        QPushButton *deleteBtn = new QPushButton("删除");
        
        QHBoxLayout *layout = new QHBoxLayout();
        layout->addWidget(editBtn);
        layout->addWidget(deleteBtn);
        layout->setContentsMargins(0, 0, 0, 0);
        
        QWidget *widget = new QWidget();
        widget->setLayout(layout);
        ui->wageTable->setCellWidget(row, 4, widget);
        
        // 连接按钮信号
        connect(editBtn, &QPushButton::clicked, [this, row]() {
            ui->wageTable->selectRow(row);
            onEditWage();
        });
        
        connect(deleteBtn, &QPushButton::clicked, [this, row]() {
            ui->wageTable->selectRow(row);
            onDeleteWage();
        });
        
        row++;
    }
}

void WageManagementDialog::onAddWage()
{
    WageEditDialog dialog(this);
    dialog.setEditMode(false);
    
    if (dialog.exec() == QDialog::Accepted) {
        QString toyName = dialog.getToyName();
        double totalWage = dialog.getTotalWage();
        double employeeWage = dialog.getEmployeeWage();
        double profit = dialog.getProfit();
        
        if (toyName.isEmpty()) {
            QMessageBox::warning(this, "警告", "请选择玩具名称");
            return;
        }
        
        // 检查是否已存在该玩具的工价记录
        QSqlQuery checkQuery;
        checkQuery.prepare("SELECT COUNT(*) FROM wage_management WHERE toy_id = ?");
        checkQuery.addBindValue(m_toyMap[toyName]);
        
        if (!checkQuery.exec() || !checkQuery.next()) {
            QMessageBox::critical(this, "错误", "检查工价记录失败: " + checkQuery.lastError().text());
            return;
        }
        
        if (checkQuery.value(0).toInt() > 0) {
            QMessageBox::warning(this, "警告", "该玩具的工价记录已存在，请使用编辑功能修改");
            return;
        }
        
        // 插入新的工价记录
        QSqlQuery insertQuery;
        insertQuery.prepare("INSERT INTO wage_management (toy_id, total_wage, employee_wage, profit) "
                           "VALUES (?, ?, ?, ?)");
        insertQuery.addBindValue(m_toyMap[toyName]);
        insertQuery.addBindValue(totalWage);
        insertQuery.addBindValue(employeeWage);
        insertQuery.addBindValue(profit);
        
        if (!insertQuery.exec()) {
            QMessageBox::critical(this, "错误", "添加工价记录失败: " + insertQuery.lastError().text());
            return;
        }
        
        // 重新加载数据
        loadWageData();
        
        QMessageBox::information(this, "成功", "工价记录添加成功");
    }
}

void WageManagementDialog::onEditWage()
{
    int currentRow = ui->wageTable->currentRow();
    if (currentRow < 0) {
        QMessageBox::warning(this, "警告", "请选择要编辑的记录");
        return;
    }
    
    // 获取选中行的数据
    int wageId = ui->wageTable->item(currentRow, 0)->data(Qt::UserRole).toInt();
    QString toyName = ui->wageTable->item(currentRow, 0)->text();
    double totalWage = ui->wageTable->item(currentRow, 1)->text().toDouble();
    double employeeWage = ui->wageTable->item(currentRow, 2)->text().toDouble();
    double profit = ui->wageTable->item(currentRow, 3)->text().toDouble();
    
    WageEditDialog dialog(this);
    dialog.setEditMode(true, wageId);
    dialog.setWageData(toyName, totalWage, employeeWage, profit);
    
    if (dialog.exec() == QDialog::Accepted) {
        QString toyName = dialog.getToyName();
        double totalWage = dialog.getTotalWage();
        double employeeWage = dialog.getEmployeeWage();
        double profit = dialog.getProfit();
        int wageId = dialog.getWageId();
        
        if (toyName.isEmpty()) {
            QMessageBox::warning(this, "警告", "请选择玩具名称");
            return;
        }
        
        // 更新工价记录
        QSqlQuery updateQuery;
        updateQuery.prepare("UPDATE wage_management SET toy_id = ?, total_wage = ?, employee_wage = ?, profit = ? "
                           "WHERE id = ?");
        updateQuery.addBindValue(m_toyMap[toyName]);
        updateQuery.addBindValue(totalWage);
        updateQuery.addBindValue(employeeWage);
        updateQuery.addBindValue(profit);
        updateQuery.addBindValue(wageId);
        
        if (!updateQuery.exec()) {
            QMessageBox::critical(this, "错误", "更新工价记录失败: " + updateQuery.lastError().text());
            return;
        }
        
        // 重新加载数据
        loadWageData();
        
        QMessageBox::information(this, "成功", "工价记录更新成功");
    }
}

void WageManagementDialog::onDeleteWage()
{
    int currentRow = ui->wageTable->currentRow();
    if (currentRow < 0) {
        QMessageBox::warning(this, "警告", "请选择要删除的记录");
        return;
    }
    
    QString toyName = ui->wageTable->item(currentRow, 0)->text();
    
    int result = QMessageBox::question(this, "确认", "确定要删除玩具 '" + toyName + "' 的工价记录吗？");
    if (result != QMessageBox::Yes) {
        return;
    }
    
    int wageId = ui->wageTable->item(currentRow, 0)->data(Qt::UserRole).toInt();
    
    QSqlQuery deleteQuery;
    deleteQuery.prepare("DELETE FROM wage_management WHERE id = ?");
    deleteQuery.addBindValue(wageId);
    
    if (!deleteQuery.exec()) {
        QMessageBox::critical(this, "错误", "删除工价记录失败: " + deleteQuery.lastError().text());
        return;
    }
    
    // 重新加载数据
    loadWageData();
    
    QMessageBox::information(this, "成功", "工价记录删除成功");
}

void WageManagementDialog::onSearch()
{
    int toyId = ui->toySearchCombo->currentData().toInt();
    
    ui->wageTable->setRowCount(0);
    
    QString sql = "SELECT wm.id, t.name, wm.total_wage, wm.employee_wage, wm.profit "
                  "FROM wage_management wm "
                  "JOIN toys t ON wm.toy_id = t.id ";
    
    // 如果选择了具体的玩具，则添加筛选条件
    if (toyId > 0) {
        sql += " WHERE t.id = ? ";
    }
    
    sql += " ORDER BY t.name";
    
    QSqlQuery query;
    query.prepare(sql);
    
    // 如果选择了具体的玩具，则绑定参数
    if (toyId > 0) {
        query.addBindValue(toyId);
    }
    
    if (!query.exec()) {
        QMessageBox::critical(this, "错误", "搜索工价记录失败: " + query.lastError().text());
        return;
    }
    
    int row = 0;
    while (query.next()) {
        int id = query.value(0).toInt();
        QString toyName = query.value(1).toString();
        double totalWage = query.value(2).toDouble();
        double employeeWage = query.value(3).toDouble();
        double profit = query.value(4).toDouble();
        
        ui->wageTable->insertRow(row);
        
        // 玩具名称
        QTableWidgetItem *toyItem = new QTableWidgetItem(toyName);
        toyItem->setData(Qt::UserRole, id); // 存储工价记录ID
        ui->wageTable->setItem(row, 0, toyItem);
        
        // 总工价 (精确到厘)
        QTableWidgetItem *totalWageItem = new QTableWidgetItem(QString::number(totalWage, 'f', 3));
        ui->wageTable->setItem(row, 1, totalWageItem);
        
        // 员工工价 (精确到厘)
        QTableWidgetItem *employeeWageItem = new QTableWidgetItem(QString::number(employeeWage, 'f', 3));
        ui->wageTable->setItem(row, 2, employeeWageItem);
        
        // 利润 (精确到厘)
        QTableWidgetItem *profitItem = new QTableWidgetItem(QString::number(profit, 'f', 3));
        ui->wageTable->setItem(row, 3, profitItem);
        
        // 操作按钮
        QPushButton *editBtn = new QPushButton("编辑");
        QPushButton *deleteBtn = new QPushButton("删除");
        
        QHBoxLayout *layout = new QHBoxLayout();
        layout->addWidget(editBtn);
        layout->addWidget(deleteBtn);
        layout->setContentsMargins(0, 0, 0, 0);
        
        QWidget *widget = new QWidget();
        widget->setLayout(layout);
        ui->wageTable->setCellWidget(row, 4, widget);
        
        // 连接按钮信号
        connect(editBtn, &QPushButton::clicked, [this, row]() {
            ui->wageTable->selectRow(row);
            onEditWage();
        });
        
        connect(deleteBtn, &QPushButton::clicked, [this, row]() {
            ui->wageTable->selectRow(row);
            onDeleteWage();
        });
        
        row++;
    }
}

void WageManagementDialog::onResetSearch()
{
    ui->toySearchCombo->setCurrentIndex(0);  // 重置为"全部"
    loadWageData();
}

void WageManagementDialog::validateInput()
{
    // 编辑和删除按钮只有在有选中行时才启用
    bool hasSelection = ui->wageTable->currentRow() >= 0;
    // 注意：我们已经移除了独立的编辑和删除按钮，所以这里不需要设置它们的状态
}